<?php
/**
 * 创建固定测试用户并添加会员数据
 */

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/support/bootstrap.php';

use think\facade\Db;

echo "🔧 创建固定测试用户...\n";

try {
    $testEmail = 'testapi_fixed@example.com';
    $testPassword = 'password123';
    
    // 检查用户是否已存在
    $existingUser = Db::name('gf_et_users')
        ->where('email', $testEmail)
        ->find();
    
    if ($existingUser) {
        echo "✅ 固定测试用户已存在: ID={$existingUser['id']}\n";
        $userId = $existingUser['id'];
    } else {
        echo "📋 创建新的固定测试用户...\n";
        
        // 创建用户数据
        $userData = [
            'email' => $testEmail,
            'password' => sha1($testPassword), // 使用与系统相同的加密方式
            'status' => 1,
            'token' => '',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'is_del' => 0
        ];
        
        $userId = Db::name('gf_et_users')->insertGetId($userData);
        echo "✅ 固定测试用户创建成功: ID={$userId}\n";
    }
    
    // 检查并添加会员记录
    echo "📋 检查会员记录...\n";
    $existingMembership = Db::name('gf_user_memberships')
        ->where('user_id', $userId)
        ->find();
    
    if ($existingMembership) {
        echo "⚠️  会员记录已存在，更新为有效状态\n";
        
        Db::name('gf_user_memberships')
            ->where('user_id', $userId)
            ->update([
                'plan_type' => 'basic',
                'status' => 'active',
                'start_date' => date('Y-m-d', strtotime('-1 day')),
                'end_date' => date('Y-m-d', strtotime('+1 year')),
                'auto_renew' => 1,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
    } else {
        echo "📋 创建会员记录...\n";
        
        $membershipData = [
            'user_id' => $userId,
            'plan_type' => 'basic',
            'status' => 'active',
            'start_date' => date('Y-m-d', strtotime('-1 day')),
            'end_date' => date('Y-m-d', strtotime('+1 year')),
            'auto_renew' => 1,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        Db::name('gf_user_memberships')->insert($membershipData);
    }
    
    echo "✅ 会员记录处理完成\n";
    
    // 验证结果
    echo "🔍 验证结果...\n";
    $user = Db::name('gf_et_users')->where('email', $testEmail)->find();
    $membership = Db::name('gf_user_memberships')->where('user_id', $user['id'])->find();
    
    echo "✅ 固定测试用户设置完成！\n";
    echo "   用户ID: {$user['id']}\n";
    echo "   邮箱: {$user['email']}\n";
    echo "   会员状态: {$membership['status']}\n";
    echo "   套餐类型: {$membership['plan_type']}\n";
    echo "   有效期至: {$membership['end_date']}\n";
    
} catch (\Exception $e) {
    echo "❌ 设置失败: " . $e->getMessage() . "\n";
    exit(1);
}

echo "🎉 固定测试用户创建完成！\n";